const Koa = require("koa");
const app = new Koa();
const json = require("koa-json");
const bodyparser = require("koa-bodyparser");
const jwt = require("koa-jwt");
const cors = require("koa-cors");

const index = require("./routes/index");

const { catchError } = require("./utils/catchError")
const { secret, notAuthorizedPath } = require("./config");
// 捕获全局的错误，并进行处理
app.use(catchError)

// 跨域配置（一定在 jwt 验证之前）
app.use(cors())
// jwt 验证
app.use(jwt({ secret: secret}).unless({path:notAuthorizedPath}))

// middlewares
app.use(
  bodyparser({
    enableTypes: ["json", "form", "text"],
  })
);
app.use(json());

app.use(require("koa-static")(__dirname + "/public"));

// logger
app.use(async (ctx, next) => {
  const start = new Date();
  await next();
  const ms = new Date() - start;
  console.log(`${ctx.method} ${ctx.url} - ${ms}ms`);
});

// routes
app.use(index.routes(), index.allowedMethods());

module.exports = app;
